//
//  MainViewModel.swift
//  DingDIngAuto
//
//  Created by liguandong on 2024/3/11.
//

import Foundation
class MainViewModel : ObservableObject {
    //都用分为单位
    private let defaultatWorkTimeMins : Int =  7 * 60  + 20
    private let defaultoffWorkTimeMins : Int = 14 * 60
    private let defaultRandomMin = 20 // 20分钟随机时间
    @Published var atWorkRandomMin : Int = 20 //分钟
    @Published var offWorkRandomMin : Int = 20 //分钟
    @Published var atWorkTimeMins : Int = 0
    @Published var offWorkTimeMins : Int = 0
    @Published var isSkipWeekdays : Bool = true
    
    @Published var atWorkHour : Int = 0
    @Published var atWorkMin : Int = 0
    @Published var offWorkHour : Int = 0
    @Published var offWorkMin : Int = 0
    
    private var dayTimer: Timer?
    @Published var nextWakeUpDate : Date = Date()

    init() {
        var obj = UserDefaults.standard.object(forKey: KEY_AT_WORK_TIME)
        if let obj = obj {
            atWorkTimeMins = obj as! Int
        }else{
            atWorkTimeMins = defaultatWorkTimeMins
        }
        atWorkHour = atWorkTimeMins / 60
        atWorkMin = atWorkTimeMins % 60
        obj = UserDefaults.standard.object(forKey: KEY_OFF_WORK_TIME)
        if let obj = obj {
            offWorkTimeMins = obj as! Int
        }else{
            offWorkTimeMins = defaultoffWorkTimeMins
        }
        offWorkHour = offWorkTimeMins / 60
        offWorkMin = offWorkTimeMins % 60
        
        obj = UserDefaults.standard.object(forKey: KEY_AT_WORK_RANDOM_MIN)
        if let obj = obj {
            atWorkRandomMin = obj as! Int
        }else{
            atWorkRandomMin = defaultRandomMin
        }
        
        obj = UserDefaults.standard.object(forKey: KEY_OFF_WORK_RANDOM_MIN)
        if let obj = obj {
            offWorkRandomMin = obj as! Int
        }else{
            offWorkRandomMin = defaultRandomMin
        }
        
        obj = UserDefaults.standard.object(forKey: KEY_SKIP_WEEKDAYS)
        if obj != nil {
            isSkipWeekdays = obj as! Bool
        }
        
        prepareNextWakeUpDate()
    }

    func prepareNextWakeUpDate(){
        
        
//        dayTimer?.invalidate()
//        let calendar = Calendar.current
//        let today = calendar.startOfDay(for: Date())
//        nextDayTime = calendar.date(byAdding: .day, value: 1, to: today)
//        dayTimer = Timer(fireAt: nextDayTime!, interval: 5, target: self, selector: #selector(onDateChanged), userInfo: nil, repeats: false)
//        if let timer = self.dayTimer {
//            RunLoop.current.add(timer, forMode: .common)
//        }
        let calendar = Calendar.current
        let StartDateOfToday = calendar.startOfDay(for: Date())
        let curDate = Date()
        let atWorkDate = calendar.date(byAdding: .minute,value: atWorkTimeMins, to: StartDateOfToday)!
        let offWorkDate = calendar.date(byAdding: .minute,value: offWorkTimeMins, to: StartDateOfToday)!
        
        debugPrint("curDate\(curDate)  atWorkDate \(atWorkDate) offWorkDate \(offWorkDate)")
        var targetDate : Date
        if curDate.compare(atWorkDate) == .orderedAscending {
            if atWorkRandomMin > 0{
                let randomValue = Int.random(in: 0..<atWorkRandomMin)
                targetDate = calendar.date(byAdding: .minute,value: randomValue, to: atWorkDate)!
            }else{
                targetDate = atWorkDate
            }
        }else if curDate.compare(offWorkDate) == .orderedAscending {
            if offWorkRandomMin > 0{
                let randomValue = Int.random(in: 0..<offWorkRandomMin)
                targetDate = calendar.date(byAdding: .minute,value: randomValue, to: offWorkDate)!
            }else{
                targetDate = offWorkDate
            }
        }else{
            let weekday = calendar.component(.weekday, from: curDate)
            let isFriday = weekday == 6 // 1代表周日，2代表周一，以此类推，6代表周五
            if isSkipWeekdays && isFriday{
                targetDate =  calendar.date(byAdding: .day,value: 3, to: atWorkDate)!
            }else{
                targetDate =  calendar.date(byAdding: .day,value: 1, to: atWorkDate)!
            }
           
        }
        nextWakeUpDate = targetDate

        dayTimer?.invalidate()
        dayTimer = nil
        dayTimer = Timer(fire: targetDate, interval: 0, repeats: false) {[weak self] timer in
            // 在目标日期触发的函数
            if let self = self {
                debugPrint("时间触发: 延迟1s")
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {[weak self] in
                    // 在1秒后执行的任务
                    if let self = self {
                        openDingTalkUrl()
                        self.prepareNextWakeUpDate()
                    }
                }
            }
        }
        if let timer = self.dayTimer {
            RunLoop.main.add(timer, forMode: .common)
        }
    }
    
//    @objc private func onDateChanged(){
//        debugPrint("时间触发")
//    }
    func saveData(){
        atWorkTimeMins = atWorkHour * 60  + atWorkMin
        offWorkTimeMins = offWorkHour * 60  + offWorkMin
        UserDefaults.standard.set(atWorkTimeMins, forKey:KEY_AT_WORK_TIME)
        UserDefaults.standard.set(offWorkTimeMins, forKey:KEY_OFF_WORK_TIME)
        UserDefaults.standard.set(atWorkRandomMin, forKey:KEY_AT_WORK_RANDOM_MIN)
        UserDefaults.standard.set(offWorkRandomMin, forKey:KEY_OFF_WORK_RANDOM_MIN)
        UserDefaults.standard.set(isSkipWeekdays, forKey:KEY_SKIP_WEEKDAYS)
        
        prepareNextWakeUpDate()
    }
    
    deinit{
        dayTimer?.invalidate()
        dayTimer = nil
    }
}
